package com.tenton.util;


import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName：CsvUtil
 * @Description：CSV读写工具类
 * @Author：tangdong
 * @Date：2022/10/23 20:54
 **/
@Slf4j
public class CsvUtil {

    private static final String CSV_COLUMN_SEPARATOR = ",";

    private static final String CSV_RN = "\r\n";

    private static void writeCsv(List list,String filePath){
        if (!CollectionUtils.isEmpty(list)){
            List<List<String>> objects = new ArrayList<>();
            List<String> colNames = new ArrayList<>();
            //获取类注释，作为第一行标题
            Field[] declaredFields = list.get(0).getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(ApiModelProperty.class)){
                    String colName = declaredField.getAnnotation(ApiModelProperty.class).value();
                    colNames.add(colName);
                }
            }
            for (Object obj : list) {
                Field[] fields = obj.getClass().getDeclaredFields();
                List<String> values = new ArrayList<>();
                for (int i = 0; i < fields.length; i++) {
                    //关闭JDK访问检查，提升反射速度
                    fields[i].setAccessible(true);
                    if (fields[i].isAnnotationPresent(ApiModelProperty.class)){
                        String value = null;
                        try {
                            value = String.valueOf(fields[i].get(obj));
                        } catch (IllegalAccessException e) {
                            log.error("存储CSV字段转换失败！");
                            e.printStackTrace();
                        }
                        values.add(value);
                    }
                }
                objects.add(values);
            }
            StringBuffer sb = new StringBuffer();
            String[] head = colNames.toArray(new String[colNames.size()]);
            String headStr = String.join(CSV_COLUMN_SEPARATOR, head).concat(CSV_RN);
            sb.append(headStr);
            objects.stream().forEach(item ->{
                String[] context = item.toArray(new String[item.size()]);
                String contextStr = String.join(CSV_COLUMN_SEPARATOR,context).concat(CSV_RN);
                sb.append(contextStr);
            });
            //写到本地文件
            try {
                FileOutputStream fos = new FileOutputStream(filePath);
                //CSV文件默认编码模式 GBK
                fos.write(sb.toString().getBytes("GBK"));
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
